# 基础系统配置
set(CMAKE_SYSTEM_NAME Generic)
set(CMAKE_SYSTEM_PROCESSOR cortex-m4)

# 编译工具链配置
set(CMAKE_C_COMPILER armclang)
set(CMAKE_CXX_COMPILER armclang)
set(CMAKE_ASM_COMPILER armclang)
set(CMAKE_LINKER armlink)
set(CMAKE_SIZE fromelf)
set(CMAKE_OBJCOPY arm-none-eabi-objcopy)

# try_compile 目标类型
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)

# 语言标准配置
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)


if (CMAKE_CXX_STANDARD EQUAL 20)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++20")
endif ()
if (CMAKE_CXX_STANDARD EQUAL 17)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17")
endif ()
if (CMAKE_CXX_STANDARD EQUAL 14)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")
endif ()


# 编译器通用参数
set(CORE_FLAGS
        --target=arm-arm-none-eabi
        -mcpu=${CMAKE_SYSTEM_PROCESSOR}
        -mfpu=fpv4-sp-d16
        -mfloat-abi=hard
        -fno-exceptions
        -fno-rtti
        -funsigned-char
        -fshort-enums
        -fshort-wchar
)

# 警告与优化
set(COMMON_WARNINGS
        -Wall
        -Wextra
        -Wpedantic
        -fdata-sections
        -ffunction-sections
        -Wno-invalid-utf8
        -Wno-psabi
)

set(DEBUG_OPTS "")
if (CMAKE_BUILD_TYPE STREQUAL "Debug")
    list(APPEND DEBUG_OPTS -O0 -g3 -gdwarf-3)
else ()
    list(APPEND DEBUG_OPTS -Os -g0 -gdwarf-3)
endif ()


add_compile_options(
        ${CORE_FLAGS}
        ${COMMON_WARNINGS}
        ${DEBUG_OPTS}
)

# 汇编参数
string(REPLACE ";" " " CORE_FLAGS_STR "${CORE_FLAGS}")
string(REPLACE ";" " " COMMON_WARNINGS_STR "${COMMON_WARNINGS}")
string(REPLACE ";" " " DEBUG_OPTS_STR "${DEBUG_OPTS}")
set(CMAKE_ASM_FLAGS_INIT "${CORE_FLAGS_STR} ${COMMON_WARNINGS_STR} ${DEBUG_OPTS_STR} -x assembler-with-cpp -Wa,--no-warn -masm=auto -c -MMD -MP")

# 链接器
file(GLOB_RECURSE LINK_SCRIPT CONFIGURE_DEPENDS ${CMAKE_CURRENT_LIST_DIR}/*.sct)

set(LINKER_CORE_FLAGS
        "--cpu=${CMAKE_SYSTEM_PROCESSOR}"
        "--map"
        "--scatter=${LINK_SCRIPT}"
        "--info=totals"
        "--info=unused"
        "--info=veneers"
        "--list=output.map"
        "--info=summarysizes"
        "--summary_stderr"
)

string(JOIN " " LINKER_FLAGS_STR ${LINKER_CORE_FLAGS})
set(CMAKE_EXE_LINKER_FLAGS_INIT "${LINKER_FLAGS_STR}")

# 设置输出文件后缀为 .elf
set(CMAKE_EXECUTABLE_SUFFIX .elf)